import api from '@/api/index'
import config from '@/config'

const state = {
  token: localStorage.getItem('token') || '',
  userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
  isLoggedIn: localStorage.getItem('isLoggedIn') === 'true'
}

const getters = {
  isLoggedIn: state => state.isLoggedIn,
  userId: state => (state.userInfo ? state.userInfo.id : null),
  userAvatar: state => {
    if (!state.userInfo || !state.userInfo.avatarUrl) {
      console.log('用户头像为空');
      return '';
    }
    
    // 使用配置文件中的方法获取正确的头像URL
    const avatarUrl = state.userInfo.avatarUrl;
    console.log('原始头像URL:', avatarUrl);
    
    // 处理头像URL
    const result = config.getAvatarUrl(avatarUrl);
    console.log('处理后的头像URL:', result);
    
    return result;
  },
  userName: state => (state.userInfo ? (state.userInfo.nickname || state.userInfo.username) : ''),
  userInfo: state => state.userInfo || {},
  isAdmin: state => (state.userInfo && state.userInfo.isAdmin === 1)
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    localStorage.setItem('token', token)
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    state.isLoggedIn = !!userInfo.username
    
    // 自动同步用户角色与管理员状态
    if (userInfo && userInfo.isAdmin === 1) {
      localStorage.setItem('userRole', 'ADMIN')
    } else {
      localStorage.setItem('userRole', 'USER')
    }
    
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    localStorage.setItem('isLoggedIn', !!userInfo.username)
  },
  CLEAR_USER: (state) => {
    state.token = ''
    state.userInfo = {}
    state.isLoggedIn = false
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('userRole')
    localStorage.removeItem('username')
  },
  UPDATE_USER: (state, userData) => {
    state.userInfo = { ...state.userInfo, ...userData }
    localStorage.setItem('userInfo', JSON.stringify(state.userInfo))
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
    state.isLoggedIn = !!userInfo.username
    
    // 自动同步用户角色与管理员状态
    if (userInfo && userInfo.isAdmin === 1) {
      localStorage.setItem('userRole', 'ADMIN')
    } else {
      localStorage.setItem('userRole', 'USER')
    }
    
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    localStorage.setItem('isLoggedIn', !!userInfo.username)
  }
}

const actions = {
  // 用户登录
  async login({ commit, dispatch }, userInfo) {
    console.log('登录操作开始，用户信息:', userInfo)
    const { username, password } = userInfo
    
    return new Promise((resolve, reject) => {
      api.user.login(username, password)
        .then(response => {
          console.log('登录API响应:', response)
          if (response.code === 0) {
            // 保存用户名到localStorage，供模拟数据使用
            localStorage.setItem('username', username);
            
            // 成功登录，生成token格式：用户已登录-username-timestamp
            // 修改token格式，确保格式为: 用户已登录-username-timestamp
            const token = '用户已登录-' + username + '-' + Date.now()
            commit('SET_TOKEN', token)
            
            // 构造基本的用户信息
            const userInfo = {
              username: username,
              nickname: username,
              avatar: '',
              roles: ['user'] // 假设默认角色为普通用户
            }
            
            // 存储用户信息
            commit('SET_USER_INFO', userInfo)
            
            // 尝试获取用户详细信息（如果后端支持）
            dispatch('getInfo').catch(error => {
              console.warn('获取用户详情失败，使用基本信息:', error)
            })
            
            resolve(response)
          } else {
            reject(new Error(response.message || '登录失败'))
          }
        })
        .catch(error => {
          console.error('登录失败:', error)
          reject(error)
        })
    })
  },

  // 用户注册
  async register(_, userInfo) {
    console.log('注册操作开始，用户信息:', userInfo)
    
    return new Promise((resolve, reject) => {
      api.user.register(userInfo)
        .then(response => {
          console.log('注册API响应:', response)
          if (response.code === 0) {
            resolve(response)
          } else {
            reject(new Error(response.message || '注册失败'))
          }
        })
        .catch(error => {
          console.error('注册失败:', error)
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      api.user.getInfo()
        .then(response => {
          if (response.code === 0) {
            const userInfo = response.data
            commit('SET_USER_INFO', userInfo)
            resolve(userInfo)
          } else {
            reject(new Error(response.message || '获取用户信息失败'))
          }
        })
        .catch(error => {
          console.error('获取用户信息失败:', error)
          reject(error)
        })
    })
  },

  // 更新用户资料
  updateProfile({ commit }, profileData) {
    return new Promise((resolve, reject) => {
      // 构建表单数据
      const formData = new URLSearchParams()
      
      // 添加所有字段
      if (profileData.nickname) formData.append('nickname', profileData.nickname)
      if (profileData.email) formData.append('email', profileData.email)
      if (profileData.remark) formData.append('remark', profileData.remark)
      if (profileData.avatarUrl) formData.append('avatarUrl', profileData.avatarUrl)
      
      api.user.updateProfile(formData)
        .then(response => {
          if (response.code === 0) {
            // 如果服务器返回了更新后的用户信息
            if (response.data) {
              commit('SET_USER_INFO', response.data)
            } else {
              // 如果服务器没有返回完整用户信息，仅更新本地的修改部分
              commit('UPDATE_USER', profileData)
            }
            resolve(response)
          } else {
            reject(new Error(response.message || '更新资料失败'))
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 修改密码
  changePassword(_, passwordData) {
    return new Promise((resolve, reject) => {
      api.user.changePassword(passwordData)
        .then(response => {
          if (response.code === 0) {
            resolve(response)
          } else {
            reject(new Error(response.message || '修改密码失败'))
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 退出登录
  async logout({ commit }) {
    return new Promise((resolve) => {
      try {
        // 先清除本地用户信息
        commit('CLEAR_USER')
        
        // 然后调用后端登出接口
        api.user.logout()
          .then(() => {
            resolve()
          })
          .catch(error => {
            console.warn('后端登出接口调用失败，但已清除本地用户信息', error)
            resolve()
          })
      } catch (error) {
        console.error('登出过程发生错误:', error)
        // 即便出错，也要保证用户被登出
        commit('CLEAR_USER')
        resolve()
      }
    })
  },

  // 上传头像并更新用户资料
  uploadAvatar({ commit }, formData) {
    return new Promise((resolve, reject) => {
      // 使用上传API
      api.upload.uploadAvatar(formData)
        .then(response => {
          if (response.code === 0 && response.data) {
            const avatarUrl = response.data
            // 更新本地状态
            commit('UPDATE_USER', { avatarUrl })
            resolve(avatarUrl)
          } else {
            reject(new Error(response.message || '上传头像失败'))
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户个人信息
  async getUserProfile({ commit }) {
    try {
      // 调用API获取用户信息
      const response = await api.user.getInfo();
      
      if (response.code === 0 && response.data) {
        // 更新用户信息
        commit('setUserInfo', response.data);
        return response.data;
      } else {
        console.error('获取用户信息失败:', response);
        return null;
      }
    } catch (error) {
      console.error('获取用户信息接口异常:', error);
      return null;
    }
  },

  // 关注用户
  followUser(_, userId) {
    // eslint-disable-next-line no-unused-vars
    return new Promise((resolve, reject) => {
      api.user.followUser(userId)
        .then(response => {
          resolve(response.data.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 取消关注用户
  unfollowUser(_, userId) {
    // eslint-disable-next-line no-unused-vars
    return new Promise((resolve, reject) => {
      api.user.unfollowUser(userId)
        .then(response => {
          resolve(response.data.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户关注列表
  getFollowingList(_, userId) {
    // eslint-disable-next-line no-unused-vars
    return new Promise((resolve, reject) => {
      api.user.getFollowingList(userId)
        .then(response => {
          resolve(response.data.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户粉丝列表
  getFollowersList(_, userId) {
    // eslint-disable-next-line no-unused-vars
    return new Promise((resolve, reject) => {
      api.user.getFollowersList(userId)
        .then(response => {
          resolve(response.data.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
} 